# -*- coding: utf-8 -*-


import requests
import json

import sys
from typing import List
from loguru import logger
import time
import requests
import re
from alibabacloud_alidns20150109.client import Client as Alidns20150109Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_alidns20150109 import models as alidns_20150109_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient



username = 'xx'
psd = 'xx'
access_key_id= "xx"
access_key_secret= "xx"
mydomain ='xx'
mydomain_rr = 'xx'
wanip = 0

"""
logger.debug()
logger.info()
logger.warning()
logger.error()
logger.info()
logger.success()
logger.critical()
"""
logger.add('my_log.log')


###登录电信光猫获取cookie
def get_cookie():
    s = requests.session()
    res = s.post("http://192.168.1.1/cgi-bin/luci", data={'username': username, 'psd': psd},
                 allow_redirects=False)
    #return(s.cookies.items()[0][0]+'='+s.cookies.items()[0][1])
    return s.cookies

###在电信光猫上查询wan ip
def get_wanip():
    global wanip
    cookie = get_cookie()
    s = requests.session()
    res = s.get("http://192.168.1.1/cgi-bin/luci/admin/settings/gwinfo?get=part",cookies=cookie)
    data = res.json()['WANIP']

    r = '^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]).(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]).(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]).(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$'
    if re.match(r, data):
        wanip = data
    else:
        logger.info("检查本地wanip格式失败： "+ str(wanip))

    logger.info("本地查询到wanip: " +str(wanip))






def create_client(access_key_id: access_key_id,access_key_secret: access_key_secret,) -> Alidns20150109Client:
    config = open_api_models.Config(
        # 您的 AccessKey ID,
        access_key_id=access_key_id,
        # 您的 AccessKey Secret,
        access_key_secret=access_key_secret
    )
    # 访问的域名
    config.endpoint = f'alidns.cn-beijing.aliyuncs.com'
    return Alidns20150109Client(config)


# 解析出查询结果中的ip和id，
def alex_data(value):
    #该域名解析条数
    total_count_record = value.body.total_count
    if total_count_record == 1:
        body_data = value.body.domain_records.record[0]
        ip = body_data.value
        record_id = body_data.record_id
        logger.info("aliyun查询结果： "+str([ip,record_id]))
        return ([ip,record_id])
    else:
        logger.error("no total_count_record value,no ip and record_id")
        return(0)


#获取阿里云上的ip
def getaliyunip():
    client = create_client(access_key_id, access_key_secret)
    describe_sub_domain_records_request = alidns_20150109_models.DescribeSubDomainRecordsRequest(sub_domain=mydomain)
    runtime = util_models.RuntimeOptions()
    try:
        value = client.describe_sub_domain_records_with_options(describe_sub_domain_records_request, runtime)
        #print(value)
        aliyunip = alex_data(value)

        if wanip != 0 :
            if aliyunip[0] == wanip:
                logger.info("比对ip一致，不执行修改")
            else:
                logger.info("比对ip不一致，需要执行修改")
                changealyunip(wanip,aliyunip[1])
        else:
            logger.error("本地未查询到wanip,不操作")

    except Exception as error:
        # 如有需要，打印 error
        UtilClient.assert_as_string(error.message)
        logger.error(["报错",UtilClient.assert_as_string(error.message)])




#更改阿里云域名解析ip
def changealyunip(ip,record_id):
    client = create_client(access_key_id, access_key_secret)
    update_domain_record_request = alidns_20150109_models.UpdateDomainRecordRequest(
        rr=mydomain_rr,
        type='A',
        value=ip,
        record_id=record_id
    )
    runtime = util_models.RuntimeOptions()
    try:
        value = client.update_domain_record_with_options(update_domain_record_request, runtime)
        if value.body.record_id == record_id:
            logger.info(["修改成功",record_id])
        else:
            logger.error("修改不成功，可能存在")

    except Exception as error:
        UtilClient.assert_as_string(error.message)
        logger.error(["修改报错",UtilClient.assert_as_string(error.message)])


def main():
    get_wanip()
    getaliyunip()


if __name__ == '__main__':
    logger.info("___________________________________________________")
    main()
